package com.qf.openapi.web.master.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.BiConsumer;

@WebFilter("/*")
@Slf4j
public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 打印当前请求的路径
        final String requestURI = req.getRequestURI();
        log.debug("requestURI={}",requestURI);
        // 把请求对象中的信息(请求头，请求的参数)  打印到日志中
        log.debug("header部分信息");
        final Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headname = headerNames.nextElement();
            final String headerVaule = req.getHeader(headname);
            log.debug("{}==={}",headname,headerVaule);
        }
        // 把本次请求对应的响应对象的相关信息，（状态码）打印到日志中
        final Map<String, String[]> parameterMap = req.getParameterMap();
        log.debug("param部分信息");
        parameterMap.forEach(new BiConsumer<String, String[]>() {
            @Override
            public void accept(String key, String[] value) {
                log.debug("{}----->{}",key,value);
            }
        });
        // 把请求放行
        chain.doFilter(request,response);

        // 把response对象的状态码打印到日志中
        final int status = resp.getStatus();
        log.debug("请求 {} 的响应状态码为:{}",requestURI,status);
    }

    @Override
    public void destroy() {

    }
}
